﻿using LY.Common.Utils.Sf_Struct;
using LY.Entity;
using LY.Entity.Entities;
using LY.Entity.Jsons;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Interface;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using LY.ShengPayApi.Model;

namespace QJ.CMS.Areas.Admin.Controllers
{
    public class ProjectMgrController : BaseController
    {
        //
        // GET: /Admin/ProjectMgr/
        private IProjectService _projectService;
        private IMemberService _memberService;
        private IProjectItemService _proItem;
        private ICompanyService _companyService;

        private static string _merchantNo = ConfigurationManager.AppSettings["merchantNo"];
        private static string _backAddress = ConfigurationManager.AppSettings["BackAddress"];
        private static string _apiAddress = ConfigurationManager.AppSettings["ApiAddress"];

        public ProjectMgrController(IProjectService projectService, IMemberService memberService, IProjectItemService itemService,ICompanyService companyService)
        {
            _projectService = projectService;
            _memberService = memberService;
            _proItem = itemService;
            _companyService = companyService;
        }

        #region 项目分类
        public ActionResult ProjectClassList()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ProjectClassList(FormCollection collection)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string colsinfo = collection["colsinfo"];
            PagedList<R_ProjectClass> bList = _projectService.QueryProjectClass(view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<R_ProjectClass>(bList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        public ActionResult ProjectClassEdit(int? Id)
        {
            R_ProjectClass projectClass = null;
            if (Id.HasValue)
            {
                projectClass = _projectService.GetModel(Id.Value);
            }
            else
            {
                projectClass = new R_ProjectClass();
            }
            return View(projectClass);
        }

        //项目类型的保存
        public ActionResult ProjectClassSave(R_ProjectClass projectClass)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                int ret = _projectService.SaveProjectClass(projectClass);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);

        }

        /// <summary>
        /// 项目类型删除操作
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ProjectClassDelete(int id, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                    return Json(rMsg);
                }

                int ret = _projectService.DeleteProjectClass(id);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        #endregion

        #region 项目审核
        //展示所有待审核的项目
        public ActionResult ProjectIndex()
        {
            return View();
        }

        //展示所有审核未通过的项目
        public ActionResult ProjectNoPassIndex()
        {
            return View();
        }

        //展示所有众筹已成功的项目
        public ActionResult ProjectSucceedIndex()
        {
            return View();
        }

        //展示所有失败了的众筹项目
        public ActionResult ProjectFailureIndex()
        {
            return View();
        }

        public ActionResult ProjectList(FormCollection collection, ProjectSearch search)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string colsinfo = collection["colsinfo"];
            collection.Add("sortname", "biaoNo");
            collection.Add("sortorder", "desc");
            PagedList<ProjectEx> bList = _projectService.QueryProject(search, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<ProjectEx>(bList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        public ActionResult ProjectEdit(int id)
        {
            R_Project project = null;
            U_Member member = null;
            U_Company company = null;
            if (id > 0)
            {
                project = _projectService.GetProject(id);
                member = _memberService.GetMember(project.MemberId);
                company = _companyService.GetCompany(project.MemberId);
            }
            else
            {
                project = new R_Project();
            }
            ViewBag.member = member;
            ViewBag.company = company;
            return View(project);
        }

        public ActionResult ProjectAuditing(int id)
        {
            R_Project project = _projectService.GetProject(id);
            ViewBag.UserName = this.LoginUser.UserName;
            return View(project);
        }

        public ActionResult ReturnToAuditing(int id)
        {
            R_Project project = _projectService.GetProject(id);
            project.ProjectStatus = 1;
            int ret = _projectService.SaveProject(project);
            return RedirectToAction("ProjectNoPassIndex");
        }

        [HttpPost]
        [ValidateInput(false)]
        //public ActionResult ProjectSave(R_Project project, string PassOrNo)
        public JsonResult ProjectSave(int id, string PassOrNo, string RefuseReason, string BeginTime)
        {
            JsonSMsg rMsg = new JsonSMsg();
            bool result = false;
            try
            {
                R_Project project = _projectService.GetProject(id);
                R_Project saveproject = _projectService.GetProject(id); 
                saveproject.RefuseReason = RefuseReason;
                if (BeginTime != "" && BeginTime != null)
                {
                    saveproject.BeginTime = Convert.ToDateTime(BeginTime);

                }
                project.UserId = this.LoginUser.ID;
                if (PassOrNo == "pass") //审核通过
                {
                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.初选 ||
                        project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.审核退回)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.审核;
                    }

                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.审核 ||
                        project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.评审退回 ||
                        project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.项目库撤回 ||
                        project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.发布成功撤回)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.评审;
                    }

                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.评审)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.发布;
                    }
                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.发布)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.发布成功;

                       // saveproject.ProjectStatus = (int)LY.Common.Enum.ProjectStatus.已审核;
                        //这里调用发标的接口
                        //result = FaBiao(project.Id);

                        //if (!result)
                        //{
                        //    rMsg.Status = -1;
                        //    rMsg.Message = "标发送失败！";
                        //    return Json(rMsg);
                        //    ;
                        //}
                        }

                }
                if (PassOrNo == "no") //审核不通过
                {

                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.初选 ||
                        project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.审核退回)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.初选退回;
                       // saveproject.ProjectStatus = (int)LY.Common.Enum.ProjectStatus.不通过;
                    }

                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.审核 ||
                        project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.评审退回 ||
                        project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.项目库撤回 ||
                        project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.发布成功撤回)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.审核退回;
                    }

                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.评审)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.评审退回;

                    }

                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.发布)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.项目库撤回;
                    }

                    if (project.AuditStatus == (int)LY.Common.Enum.ProjectStatus.发布成功)
                    {
                        saveproject.AuditStatus = (int)LY.Common.Enum.ProjectStatus.发布成功撤回;
                    }
                   
                }
                saveproject.AuditTime = DateTime.Now;

                 
                   //插入流程记录表 
                {
                    var flow = new R_ProjectFlow
                        {
                            AuditTime = project.AuditTime,
                            AuditUser = this.LoginUser.UserName,
                            ProjectId = project.Id,
                            Content1 = project.RefuseReason,
                            Status = (int)saveproject.AuditStatus
                        };
                    _projectService.InsertPorjectFlow(flow);
                }

                int ret = _projectService.SaveProject(saveproject);


                 


                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            //rMsg.Data = Url.Action("ProjectIndex", new { projectStatus = 1 });

            return Json(rMsg);
        }



 

        #endregion

        #region 众筹项目

        //众筹中的项目
        public ActionResult CrowdfundingProject()
        {
            return View();
        }

        public ActionResult SelectCrowdfundingProject()
        {
            return View();
        }

        //展示一个项目的档位列表
        public ActionResult ProjectItemList(int id)
        {
            ViewBag.ProjectId = id; //传递项目Id 到前台
            return View();
        }

        [HttpPost]
        public ActionResult ProjectItemList(FormCollection collection, int projectId)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string colsinfo = collection["colsinfo"];
            var bList = _projectService.QueryProjectItem(view, projectId);
            JsonQTable at = JsonQTable.ConvertFromPagedList<R_ProjectItem_EX>(bList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        //项目投资档位编辑
        public ActionResult ProjectItemEdit()
        {
            R_ProjectItem projectItem = null;
            int id;
            if (Request["id"] != null)
            {
                id = Convert.ToInt32((Request["id"]));
                projectItem = _projectService.GetProjectItem(id);
            }
            else
            {
                projectItem = new R_ProjectItem();
                projectItem.ProjectId = Convert.ToInt32((Request["projectId"]));
            }
            return View(projectItem);
        }

        //项目投足档位保存
        public ActionResult ProjectItemSave(R_ProjectItem projectItem)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                int ret = _projectService.SaveProjectItem(projectItem);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";

                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //删除投资档位
        public ActionResult DeleteItem(int id)
        {
            JsonSMsg msg = new JsonSMsg();
            try
            {
                int ret = _proItem.deleteProjectItem(id);
                if (ret > 0)
                {
                    msg.Status = 1;
                    msg.Message = "删除成功！";

                }
                else
                {
                    msg.Status = -1;
                    msg.Message = "操作失败！";
                }
            }
            catch (Exception ex)
            {
                msg.Status = -1;
                msg.Message = ex.Message;
            }
            return Json(msg);
        }


        public ActionResult ProjectItemInvestment()
        {
            int projectItemId = Convert.ToInt32(Request["id"]);
            R_ProjectItem projectItem = _projectService.GetProjectItem(projectItemId);
            ViewBag.ProjectId = projectItem.ProjectId;
            ViewBag.ProjectItemId = projectItemId;
            return View();
        }

        //众筹投资细节
        public ActionResult ProjectOrderList(int id)
        {
            ViewBag.ProjectId = id;
            ViewBag.projectBiaoNo = _projectService.GetProject(id).BiaoNo;
            return View();
        }

        //众筹订单列表
        [HttpPost]
        public ActionResult ProjectOrderList(FormCollection collection, ProjectOrderSearch search)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string colsinfo = collection["colsinfo"];
           var bList = _projectService.QueryProjectOrder(view, search);
            JsonQTable at = JsonQTable.ConvertFromPagedList<R_ProjectOrder_EX>(bList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        public ActionResult ProjectOrderEdit(int? id)
        {
            R_ProjectOrder projectOrder = null;
            if (id.HasValue)
            {
                projectOrder = _projectService.GetProjectOrder((int)id);
            }
            else
            {
                projectOrder = new R_ProjectOrder();
            }
            return View(projectOrder);
        }

        public ActionResult ProjectOrderSave(R_ProjectOrder projectOrder)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                int ret = _projectService.SaveProjectOrder(projectOrder);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        public ActionResult CloseOrder(string orderid)
        {
            var rMsg = new JsonSMsg();
            try
            {
                int ret = _projectService.UpdateOrderPayStatus((int)LY.Common.Enum.PayStatus.交易关闭, orderid);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        public ActionResult RefundOrder(string projectNo, string orderNo)
        {
            var rMsg = new JsonSMsg();
            try
            {
                int ret = 0;
                var strJson = LY.ShengPayApi.Services.Delete.DeleteP2PBidSubmitBid(_apiAddress, _merchantNo, projectNo,
                                                                                   orderNo);
                if (strJson.Contains("请求成功完成"))
               {
                   ret = _projectService.UpdateOrderPayStatus((int)LY.Common.Enum.PayStatus.退款成功, orderNo);
               }
                 
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        #endregion

        #region 发布众筹标

        public bool FaBiao(int projectId)
        {
            R_Project project = _projectService.GetProject(projectId);
            U_Member member = _memberService.getMemberInfo(project.MemberId); //获取发布该众筹标的人

            ZCProject zcProject = new ZCProject
                {
                    SFTUserName = member.SFTUserName,
                    Amount = project.Amount,
                    BiaoNo = project.BiaoNo,
                    CollectDays = project.CollectDays,
                    ProjectName = project.ProjectName
                };

            string strJson = LY.ShengPayApi.Services.Put.PutP2PBid(_apiAddress, _merchantNo, zcProject);
            if (strJson.Contains("请求成功完成"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 满标/流标

        public ActionResult ManBiao(int projectId, int eventType)
        {
            //R_Project project = _projectService.GetProject(projectId);
            //U_Member member = _memberService.getMemberInfo(project.MemberId); //获取发布该众筹标的人


            //ZCProject zcProject = new ZCProject
            //{
            //    SFTUserName = member.SFTUserName,
            //    Amount = project.Amount,
            //    BiaoNo = project.BiaoNo,
            //    CollectDays = project.CollectDays,
            //    ProjectName = project.ProjectName
            //};
            ////string strJson = LY.ShengPayApi.Services.Put.PutP2PBidEvent(_apiAddress, _merchantNo, eventType,
            ////                                                            _backAddress, zcProject);

            //if (strJson.Contains("请求成功完成") && eventType == 1)
            //{
            //    project.ProjectStatus = 6; //已失败
            //    _projectService.SaveProject(project);
            //}
            //else
            //{
            //    project.ProjectStatus = 5; //已失败
            //    _projectService.SaveProject(project);
            //}


            //return Json(strJson);
            return null;

        }

        public ActionResult FenBiao(int projectId, int origOrderType)
        {
            R_Project project = _projectService.GetProject(projectId);
            U_Member member = _memberService.getMemberInfo(project.MemberId); //获取发布该众筹标的人

            var zcProject = new ZCProjectLoan
            {
                BiaoNo = project.BiaoNo,
                LoanNo = "qjzcfb_" + projectId + DateTime.Now.ToString("yyyyMMddHHmmss"),
                DealerFee = (decimal)0.00
            };

            var platformFee = Math.Round((decimal)(project.Amount * (decimal)0.03), 2);
            if (origOrderType == 1)
            {

                //第一次先扣除总额度的3%
                //付款剩余97%中的70% Math.Round((decimal)project.Amount, 2)

                var loanAmount = Math.Round((decimal)((project.Amount - platformFee) * (decimal)0.7), 2);

                zcProject.LoanAmount = loanAmount;
                zcProject.PlatformFee = platformFee;
            }
            else
            {
                //付款剩余97%中的30%
                var loanAmount = Math.Round((decimal)((project.Amount - platformFee) * (decimal)0.3), 2);
                zcProject.LoanAmount = loanAmount;
                zcProject.PlatformFee = (decimal)0.00;
            }


            string strJson = LY.ShengPayApi.Services.Put.PutLoan(_apiAddress, _merchantNo, _backAddress, zcProject);

            //if (strJson.Contains("请求成功完成") && eventType == 1)
            //{
            //    project.ProjectStatus = 6; //已失败
            //    _projectService.SaveProject(project);
            //}
            //else
            //{
            //    project.ProjectStatus = 5; //已失败
            //    _projectService.SaveProject(project);
            //}


            return Json(strJson);


        }


        #endregion


    }
}
